<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
    <el-table :data="users" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="mobile" label="手机号"></el-table-column>
      <el-table-column prop="groups[0].name" label="用户角色"></el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false; emits('deleteusers-canceled');">取消</el-button>
      <el-button type="primary" :disabled="selectedUsers.length === 0" @click="handleDelete">删除</el-button>
    </span>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listUsers, deleteUsers } from '../utils/apiUser';
const emits = defineEmits(['deleteusers-canceled', 'deleteusers-success'])
const dialogVisible = ref(false);
const dialogTitle = '删除用户';
const users = ref([]);
const selectedUsers = ref([]);
onMounted(async () => {
  await loadUsers();
});
async function loadUsers() {
  try {
    const { data } = await listUsers();
    users.value = data.filter(user => user.username !== 'current_user');
  } catch (error) {
    ElMessage.error('加载用户列表失败');
  }
}
function handleSelectionChange(selection) {
  selectedUsers.value = selection.map(item => item.id);
}
function handleDelete() {
  ElMessageBox.confirm('确认删除所选用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUsers(selectedUsers.value);
      ElMessage.success('删除成功');
      await loadUsers();
      dialogVisible.value = false;
      emits('deleteusers-success')
    } catch (error) {
      ElMessage.error('删除用户失败');
    }
  }).catch(() => {
    // 取消删除的代码
  });
}
</script>
